package com.qst.order.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.qst.order.domain.DTO.*;
import com.qst.order.domain.Order;
import com.qst.order.domain.OrderItem;
import com.qst.order.domain.VO.OrderListVO;
import com.qst.order.service.OrderItemService;
import com.qst.order.service.OrderService;
import com.qst.order.service.ProductService;
import com.qst.order.utils.JwtUtil;
import com.qst.order.utils.Result;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;


import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

import java.util.List;

@RestController
@RequestMapping("/api/order")
@RequiredArgsConstructor
@Slf4j
public class OrderController {

    private final OrderService orderService;

    private final OrderItemService orderItemService;

    private final JwtUtil jwtUtil;

    private final ProductService productService;

    //创建单个商品订单---立即购买
    @PostMapping("/create")
    @Transactional
    public Result<Order> createOrder(@RequestBody OrderCreatDTO orderCreatDTO, @RequestHeader("Authorization") String token) {
        try {
            // 解析 token 获取 userId
            String userId = jwtUtil.getClaim(token, "userId");
            if (userId == null) {
                return Result.error(401, "无效的 token");
            }
            // 调用 Service 层处理订单创建
            Order order = orderService.createOrder(orderCreatDTO, Integer.parseInt(userId));

            if (order == null) {
                return Result.error(500, "创建订单失败");
            }
            return Result.success(order);
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @PostMapping("/createBatch")
    @Transactional
    public Result<Order> createBatchOrder(@RequestBody OrderBatchRequest orderBatchRequest, @RequestHeader("Authorization") String token) {

        log.info("购物车列表:{}", orderBatchRequest);

        String userId = jwtUtil.getClaim(token, "userId");

        Order order = orderService.createBatchOrder(orderBatchRequest, Integer.parseInt(userId));

        if (order == null) {
            return Result.error("创建订单失败");
        }

        return Result.success(order);

    }

    @GetMapping("/list")
    public Result getOrderListByUserId(@RequestParam Integer page, @RequestParam Integer size,
                                       @RequestParam String status,
                                       @RequestHeader("Authorization") String token,
                                       @RequestParam(value = "orderNo",required = false)String orderNo,
                                       @RequestParam(value = "startDate",required = false) String startDate,
                                       @RequestParam(value = "endDate",required = false) String endDate
    ) {


        String userId = jwtUtil.getClaim(token, "userId");

        ///log.warn("用户ID:{}", userId);
        //log.warn("订单状态:{}", status);


        IPage<OrderListVO> orderList = orderService.getOrderList(page, size, Integer.parseInt(userId), status,orderNo,startDate,endDate);


        return Result.success(orderList);
    }

    @PostMapping("/pay")
    public Result pay(@RequestBody PayDTO payDTO, @RequestHeader("Authorization") String token) {

        String userId = jwtUtil.getClaim(token, "userId");

        boolean b = orderService.payOrder(payDTO, Integer.valueOf(userId));

        if (!b) {
            return Result.error("支付失败,余额不足");
        }
        return Result.success("支付成功");
    }

    @PostMapping("/cancel/{orderId}")
    @Transactional
    public Result cancelOrder(@PathVariable("orderId") Integer orderId) {
        boolean b = orderService.canceledOrder(orderId);
        if (!b) {
            return Result.error("只有未支付的订单才可以取消");
        }
        return Result.success();
    }

    @PostMapping("/confirmReceiveItem/{itemNo}")
    @Transactional
    public Result confirmReceive(@PathVariable("itemNo") String itemNo) {
        try {
            // 1. 更新当前订单项状态为"已送达"
            orderItemService.lambdaUpdate()
                    .set(OrderItem::getItemStatus, "delivered")
                    .set(OrderItem::getDeliverTime, LocalDateTime.now())
                    .eq(OrderItem::getItemNo, itemNo)
                    .update();

            // 2. 获取当前订单项所属的订单ID
            OrderItem currentItem = orderItemService.lambdaQuery()
                    .eq(OrderItem::getItemNo, itemNo)
                    .one();
            if (currentItem == null) {
                throw new RuntimeException("订单项不存在：" + itemNo);
            }
            Integer orderId = currentItem.getOrderId();

            // 3. 查询该订单关联的所有订单项总数
            long totalItemCount = orderItemService.lambdaQuery()
                    .eq(OrderItem::getOrderId, orderId)
                    .count();

            // 4. 根据订单项总数设置订单状态：唯一订单项则设为"已完成"，否则设为"部分收货"
            String orderStatus = totalItemCount == 1 ? "completed" : "partial_received"; // 假设"已完成"状态值为"completed"

            orderService.lambdaUpdate()
                    .set(Order::getStatus, orderStatus)
                    .set(Order::getReceiveTime, LocalDateTime.now())
                    .eq(Order::getOrderId, orderId)
                    .update();

        } catch (Exception e) {
            log.warn("更新订单状态失败:{}", e.getMessage(), e); // 补充完整堆栈日志便于排查
            throw new RuntimeException("确认收货失败", e); // 包装异常信息，更友好
        }
        return Result.success();
    }
    @PostMapping("/confirmReceiveBatch")//批量确认收货
    @Transactional
    public Result batchConfirmReceive(
            @RequestBody @Valid BatchConfirmReceiveRequest request) {
        try {
            for (OrderItemConfirm item : request.getItems()) {
                orderItemService.lambdaUpdate().set(OrderItem::getItemStatus, "delivered")
                        .set(OrderItem::getDeliverTime, LocalDateTime.now())
                        .eq(OrderItem::getItemNo,item.getItemNo()).update();
            }
            orderService.lambdaUpdate().set(Order::getStatus, "partial_received")
                    .set(Order::getReceiveTime, LocalDateTime.now())
                    .eq(Order::getOrderId,request.getOrderId())
                    .update();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return Result.success();
    }

    /**
     * 通用订单状态更新方法
     *
     * @param orderId      订单ID
     * @param targetStatus 目标状态
     * @param successMsg   成功提示消息
     * @param failMsg      失败提示消息
     * @return 统一响应结果
     */
    private Result updateOrderStatus(Integer orderId, String targetStatus, String successMsg, String failMsg) {
        // 1. 参数校验
        if (orderId == null) {
            return Result.error("订单ID不能为空");
        }
        boolean update = orderService.update(new UpdateWrapper<Order>().eq("order_id", orderId).set("status", targetStatus));

        // 4. 返回结果
        return update ? Result.success(successMsg) : Result.error(failMsg);
    }

    /**
     * 根据目标状态获取允许更新的源状态（状态流转校验）
     * 例如：取消订单只能从"pending"状态变更；确认收货只能从"shipped"状态变更
     */

    @GetMapping("/detail/{orderId}")
    public Result<OrderListVO> getOrderDetail(@PathVariable("orderId") Integer orderId) {

        OrderListVO detailOrder = orderService.getDetailOrder(orderId);

        return Result.success(detailOrder);
    }

    @GetMapping("/all")
    public Result<List<Order>> getAllOrderList(@RequestHeader("Authorization") String token) {

        String userId = jwtUtil.getClaim(token, "userId");

        List<Order> list = orderService.lambdaQuery().eq(Order::getUserId, userId).list();


        return Result.success(list);
    }
}
